//
//  AppManager.m
//  ImGuider
//
//  Created by llt on 2017/4/12.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "AppManager.h"
#import "NetClient.h"
#import "AppDelegate.h"
#import "LaunchVC.h"

#define kCityVersion @"cityVersion" // 本地存储的城市版本号
#define kCountryVersion @"countryVersion" // 本地存储的国家版本号
//#define kNetVersion @"netVersion"
#define kLastCityKey @"kLastCityKey" // 上次获取的城市
#define kLastRecomend @"Recomend" // 上次获取的推荐城市URL
//#define kCountryList @"CountryList"// 获取的按国家分组的城市

#define kTranslationArray @"kTranslationArray"
#define kLeftLanguage @"kLeftLanguage"
#define kRightLanguage @"kRightLanguage"
#define kRecentLanguage @"kRecentLanguage"

#define kSearchResult @"kSearchResult"

#define kAskPlay @"kAskPlay"
#define kAskDownload @"kAskDownload"
#define KAutomaticPlay @"automaticPlay"
#define kOffReceiver @"kOffReceiver"
#define kCurrencyCode @"kCurrencyCode"

#define kAllPlayWhenListen @"kAllPlayWhenListen"

#define kRecommendArray @"kRecommendArray"

@interface AppManager()

@end

@implementation AppManager

@synthesize baseURLStr = _baseURLStr,cityver = _cityver, countryver = _countryver, recomendParams = _recomendParams, currencyCode = _currencyCode, language = _language, lastCity = _lastCity;

+ (instancetype)sharedManager {
    
    static AppManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[AppManager alloc] init];
        
    });
    return _sharedManager;
}


- (NSString *)baseURLStr {
    
    if (!_baseURLStr) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        _baseURLStr = [defaults objectForKey:kBaseURLStr] ?: kBaseURLStr;
    }
    return _baseURLStr;
}

- (void)setBaseURLStr:(NSString *)baseURLStr {
    
    if (baseURLStr.length == 0 || [_baseURLStr isEqualToString:baseURLStr]) {
        
        return;
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:baseURLStr forKey:kBaseURLStr];
    [defaults synchronize];
    
    _baseURLStr = baseURLStr;
    [NetClient changeClient];
}

- (void)setCityver:(NSString *)cityver {
    
    if (![_cityver isEqualToString:cityver]) {
        
        [[NSUserDefaults standardUserDefaults] setObject:cityver forKey:kCityVersion];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        _cityver = cityver;
    }
}

//- (void)setCountryList:(NSArray *)countryList {
//
//    [[NSUserDefaults standardUserDefaults] setObject:countryList forKey:kCountryList];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//}

//- (NSArray *)countryList {
//
//    NSArray *arr = [NSArray modelArrayWithClass:[searchCountyList class] json:[[NSUserDefaults standardUserDefaults] arrayForKey:kCountryList]];
//
//    NSArray *sortArray = [arr sortedArrayUsingComparator:^NSComparisonResult(searchCountyList *obj1, searchCountyList *obj2) {
//
//        NSString *idx1 = [IGUtil firstCharactor:obj1.smartName];
//        NSString *idx2 = [IGUtil firstCharactor:obj2.smartName];
//
//        return [idx1 compare:idx2];
//    }];
//
//    return sortArray;
//}

- (void)setTranslationArray:(NSMutableArray *)translationArray {
    
    NSString * str = [translationArray modelToJSONString];
    
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:kTranslationArray];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSMutableArray *)translationArray {
    
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:kTranslationArray];
    
    return [NSMutableArray arrayWithArray:[NSArray modelArrayWithClass:[TranslationModel class] json:str]];
}


- (void)setLanguageLeft:(LanguageModel *)languageLeft {
    
    NSString * str = [languageLeft modelToJSONString];
    
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:kLeftLanguage];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (LanguageModel *)languageLeft {
    
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:kLeftLanguage];
    LanguageModel * model = [LanguageModel modelWithJSON:str];
    if (!str) {
        model = [LanguageModel new];
        model.lang = @"zh-CN";
        model.translation =@"zh";
        model.name = @"TRANSLATION_LANGUAGE1";
    }
    return model;
}

- (void)setLanguageRight:(LanguageModel *)languageRight {
    
    NSString * str = [languageRight modelToJSONString];
    
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:kRightLanguage];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (LanguageModel *)languageRight{
    
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:kRightLanguage];
    LanguageModel * model = [LanguageModel modelWithJSON:str];
    if (!str) {
        model = [LanguageModel new];
        model.lang = @"en-AU";
        model.translation =@"en";
        model.name = @"TRANSLATION_LANGUAGE3";
    }
    return model;
    
    
}

- (void)setRecentLanguages:(NSArray *)recentLanguages {
    
    NSString *  str = [recentLanguages modelToJSONString];
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:kRecentLanguage];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSArray *)recentLanguages {
    
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:kRecentLanguage];
    
    return  [NSMutableArray arrayWithArray:[NSArray modelArrayWithClass:[LanguageModel class] json:str]];
    
    
}

- (void)setSearchResultArray:(NSMutableArray *)searchResultArray {
    NSString * str = [searchResultArray modelToJSONString];
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:kSearchResult];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (NSMutableArray *)searchResultArray {
    
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:kSearchResult];
    
    return [NSMutableArray arrayWithArray:[NSArray modelArrayWithClass:[SearchResultModel class] json:str]];
}

- (void)setRecommendArray:(NSMutableArray<City *> *)recommendArray{
    NSString * str = [recommendArray modelToJSONString];
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:kRecommendArray];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSMutableArray<City *> *)recommendArray {
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:kRecommendArray];
    
    return [NSMutableArray arrayWithArray:[NSArray modelArrayWithClass:[City class] json:str]];
}


- (NSString *)cityver {
    
    if (!_cityver) {
        _cityver = [[NSUserDefaults standardUserDefaults] objectForKey:kCityVersion];
    }
    return _cityver;
}

- (void)setCountryver:(NSString *)countryver {
    if (![_countryver isEqualToString:countryver]) {
        
        [[NSUserDefaults standardUserDefaults] setObject:countryver forKey:kCountryVersion];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        _countryver = countryver;
    }
}

- (NSString *)countryver {
    
    if (!_countryver) {
        _countryver = [[NSUserDefaults standardUserDefaults] objectForKey:kCountryVersion];
    }
    return _countryver;
}


//- (void)setVersion:(VersionModel *)version {
//
//    [[NSUserDefaults standardUserDefaults] setObject:[version modelToJSONString] forKey:kNetVersion];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//}
//
//- (VersionModel *)version {
//
//    NSString *versionJson = [[NSUserDefaults standardUserDefaults] objectForKey:kNetVersion];
//
//    return [VersionModel modelWithJSON:versionJson];
//}



- (void)setRecomendParams:(NSDictionary *)recomendParams {
    
    if (![_recomendParams isEqualToDictionary:recomendParams]) {
        
        [[NSUserDefaults standardUserDefaults] setObject:recomendParams forKey:kLastRecomend];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        _recomendParams = recomendParams;
    }
}

- (NSDictionary *)recomendParams {
    
    if (!_recomendParams) {
        _recomendParams = [[NSUserDefaults standardUserDefaults] objectForKey:kLastRecomend];
    }
    return _recomendParams;
}

- (void)setLastCity:(City *)lastCity {
    
    _lastCity = lastCity;
    
    NSString *cityJson = [lastCity modelToJSONString];
    
    [[NSUserDefaults standardUserDefaults] setObject:cityJson forKey:kLastCityKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (City *)lastCity {
    
    if (!_lastCity) {
        NSString *cityJson = [[NSUserDefaults standardUserDefaults] objectForKey:kLastCityKey];
        
        if (cityJson) {
            _lastCity = [City modelWithJSON:cityJson];
        }
    }
    
    return _lastCity;
}

//- (void)setLastCityID:(NSNumber *)lastCityID {
//
//    if (![_lastCityID isEqualToNumber:lastCityID]) {
//
//        [[NSUserDefaults standardUserDefaults] setObject:lastCityID forKey:kLastCityID];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//
//        _lastCityID = lastCityID;
//    }
//}


//- (NSNumber *)lastCityID {
//
//    if (!_lastCityID) {
//        _lastCityID = [[NSUserDefaults standardUserDefaults] objectForKey:kLastCityID];
//    }
//    return _lastCityID;
//}

- (BOOL)allowWhenDownload {
    
    return [[NSUserDefaults standardUserDefaults] boolForKey:kAskDownload];
}

- (void)setAllowWhenDownload:(BOOL)allowWhenDownload {
    
    [[NSUserDefaults standardUserDefaults] setBool:allowWhenDownload forKey:kAskDownload];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)setIsOffReceiverWhenListen:(BOOL)isOffReceiverWhenListen {
    [[NSUserDefaults standardUserDefaults] setBool:isOffReceiverWhenListen forKey:kOffReceiver];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (BOOL)isOffReceiverWhenListen {
    
    return [[NSUserDefaults standardUserDefaults] boolForKey:kOffReceiver];
}

- (void)setAllPlayWhenListen:(BOOL)allPlayWhenListen {
    
    [[NSUserDefaults standardUserDefaults] setBool:allPlayWhenListen forKey:kAllPlayWhenListen];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (BOOL)allPlayWhenListen {
    
    return [[NSUserDefaults standardUserDefaults] boolForKey:kAllPlayWhenListen];
}

- (BOOL)allowWhenPlay {
    
    return [[NSUserDefaults standardUserDefaults] boolForKey:kAskPlay];
}

- (BOOL)automaticPlay {
    
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:KAutomaticPlay]) {
        return [[NSUserDefaults standardUserDefaults] boolForKey:KAutomaticPlay];
    }
    
    return YES;
}

- (BOOL)hasTicket {
    
#ifdef IG_AppStore
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *appVersion = kVersion;
        NSString *netVersion = [AppManager sharedManager].version.version;
        if ([appVersion compare:netVersion options:NSNumericSearch] == NSOrderedDescending) {
            
            _hasTicket = NO;
        } else {
            
            _hasTicket = YES;
        }
    });
    
    return _hasTicket;
#else
    return YES;
#endif
}

- (void)setAutomaticPlay:(BOOL)automaticPlay {
    
    [[NSUserDefaults standardUserDefaults] setBool:automaticPlay forKey:KAutomaticPlay];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)setAllowWhenPlay:(BOOL)allowWhenPlay {
    
    [[NSUserDefaults standardUserDefaults] setBool:allowWhenPlay forKey:kAskPlay];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (void)setCurrencyCode:(NSString *)currencyCode {
    
    if (![_currencyCode isEqualToString:currencyCode]) {
        
        //        NSString *currency = [[NSUserDefaults standardUserDefaults] objectForKey:kCurrencyCode];
        //        if (currency.length > 0) {
        //
        //            return;
        //        }
        
        [[NSUserDefaults standardUserDefaults] setObject:currencyCode forKey:kCurrencyCode];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [NetClient changeClient];
    }
    
    _currencyCode = currencyCode;
}

- (NSString *)currencyCode {
    
    if (!_currencyCode) {
        _currencyCode = [[NSUserDefaults standardUserDefaults] objectForKey:kCurrencyCode];
    }
    
    if (!_currencyCode) {
        if (@available(iOS 10.0, *)) {
            _currencyCode = [[NSLocale currentLocale] currencyCode];
        } else {
            NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];
            if ([localeIdentifier isEqualToString:@"zh-Hans"]) {
                _currencyCode = @"CNY";
            } else {
                _currencyCode = @"USD";
            }
        }
    }
    
    if ([_currencyCode isEqualToString:@"CNY"]) {
        return @"CNY";
    }
    
    return @"USD";
}

- (void)setupLanguageType {
    
    NSArray *langArray = [[NSUserDefaults standardUserDefaults] arrayForKey:@"AppleLanguages"];
    NSString *lan = [[langArray firstObject] lowercaseString];
    
    AppLanguageType type = AppLanguageEnglish;
    
    if ([lan hasPrefix:@"zh-hans"]) {
        
        type = AppLanguageCNJan;
    } else if ([lan hasPrefix:@"zh-hant"]) {
        
        if ([lan hasSuffix:@"hk"]) {
            
            type = AppLanguageCNFanXG;
        } else {
            
            type = AppLanguageCNFan;
        }
    } else if ([lan hasPrefix:@"ja"]) {
        
        type = AppLanguageJapanese;
    } else if ([lan hasPrefix:@"it"]) {
        
        type = AppLanguageItaliano;
    }
    
    self.language = type;
}


static NSBundle *bundle = nil;

- (void)setLanguage:(AppLanguageType)language {
    

    _language = language;
    
    self.lanstr = @"en";
    
    switch (language) {
        case AppLanguageCNJan:
            self.lanstr = @"zh-Hans";
            break;
        case AppLanguageCNFan:
            self.lanstr = @"zh-Hant";
            break;
        case AppLanguageCNFanXG:
            self.lanstr = @"zh-Hant-HK";
            break;
        case AppLanguageJapanese:
            self.lanstr = @"ja";
            break;
        case AppLanguageItaliano:
            self.lanstr = @"it";
            break;
            
        default:
            break;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:self.lanstr ofType:@"lproj"];
    bundle = [NSBundle bundleWithPath:path];

    [[NSUserDefaults standardUserDefaults] setObject:@[self.lanstr] forKey:@"AppleLanguages"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [NetClient changeClient];
}

- (NSString *)get:(NSString *)key alter:(NSString *)alternate {
    
    return [bundle localizedStringForKey:key value:alternate table:nil];
}

@end


